<?php
class Home extends CI_Controller {
    
    private $_auth;
    public function __construct() {
        parent::__construct();
        $this->_auth = $this->myclass->checkuser();
    }

    public function index(){
        if($this->_auth == TRUE) redirect("backend/home/manage","refresh");
        $post = null;
        if($this->input->post("login")){
            $post = $this->input->post('data');
            $data['data']['post'] = $post;
        }
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        $this->form_validation->set_rules('data[email]', 'Email', 'trim|required|valid_email|xss_clean');
        $this->form_validation->set_rules('data[pass]', 'Mật khẩu', 'trim|required|callback_account_check['.$post["email"].']');
        if ($this->form_validation->run() == TRUE){
            $user = $this->db->where('email',$post["email"])->get("users")->row_array();
            $this->session->set_userdata('user',$user);
            redirect("backend/home/manage");
        }        
        $data['title'] = "Đăng nhập hệ thống";
        $data['temp'] = "backend/home/login";
        $this->load->view('backend/layout/login',$data);
    }
    
    public function account_check($pass, $email) {
        $count = $this->db->from("users")->where('email', $email)->count_all_results();
        if ($count == 1) {
            $user = $this->db->from("users")->where('email', $email)->get()->row_array();
            $pass = do_hash($pass, 'md5');
            if ($pass != $user['pass']) {
                $this->form_validation->set_message('account_check', 'Email hoặc Mật khẩu không đúng');
                return FALSE;
            } else
                return TRUE;
        }
        else {
            $this->form_validation->set_message('account_check', 'Email hoặc Mật khẩu không đúng');
            return FALSE;
        }
    }
    
    public function logout(){
        if($this->_auth == FALSE) redirect("backend/home","refresh");
        $this->session->unset_userdata('user');
        redirect("backend/home");
    }
    
    public function manage(){
        if($this->_auth == FALSE) redirect("backend/home","refresh");
        $data['title'] = "Quản lý hệ thống";
        $data['temp'] = "backend/home/home";
        $data['data'] = "";
        $this->load->view('backend/layout/index',$data);
    }
    
}
